<template>
  <div class="mainua">
    <el-form
      class="demo-form-inline"
      :model="form"
      label-width="140px"
      ref="form"
      :rules="rules"
      validate-on-rule-change
    >
      <div class="main_spac1" style="padding-bottom: 5px">
        <div class="main_white padding10">
          <div class="main_crumbs boxdq">
            <div class="main_crumbs_l">
              <a href="javascript:;" @click="$router.back(-1)">
                <i class="el-icon-arrow-down"></i>返回
              </a>
              <em>|</em>
              <span>优惠券</span>
            </div>
          </div>
          <div v-loading="listLoading" element-loading-text="加载中">
            <!-- 主要部分 -->
            <div class="marginTop20 marginLeft25">
              <el-form-item label="优惠券类型：" prop="type">
                <el-select
                  class="wid240"
                  v-model="form.type"
                  placeholder="优惠券类型"
                  @change="isEdit = true"
                >
                  <el-option label="普通券" value="1"></el-option>
                  <el-option label="现金券" value="2"></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="优惠券名称：" prop="title">
                <el-input
                  class="wid240"
                  v-model="form.title"
                  placeholder="优惠券名称"
                  @change="isEdit = true"
                ></el-input>
              </el-form-item>
              <el-form-item label="使用说明：" prop="describe">
                <div style="width: 340px">
                  <el-input
                    type="textarea"
                    v-model="form.describe"
                    placeholder="使用说明"
                    maxlength="30"
                    show-word-limit
                    @change="isEdit = true"
                  ></el-input>
                </div>
              </el-form-item>
              <el-form-item label="面值：" prop="money">
                <el-input
                  class="wid240"
                  v-model="form.money"
                  placeholder="面值"
                  @change="isEdit = true"
                ></el-input>
              </el-form-item>
              <el-form-item label="发放方式：" prop="grant_type">
                <el-select
                  class="wid240"
                  v-model="form.grant_type"
                  placeholder="发放方式"
                  @change="isEdit = true"
                >
                  <el-option label="后台发放" value="1"></el-option>
                  <el-option label="用户领取" value="2"></el-option>
                  <el-option label="新用户" value="3"></el-option>
                </el-select>
              </el-form-item>
              <el-form-item prop="front_end_show" v-if="form.grant_type == 1">
                <div slot="label">
                  是否霸屏：
                  <!-- <el-tooltip
                  class="item marginRight5 mainor_tei"
                  effect="dark"
                  placement="top"
                >
                  <div slot="content">
                    是否允许参与了满减满赠，限时特卖活动的订单使用
                  </div>
                  <i class="el-icon-question"></i></el-tooltip
                >： -->
                </div>
                <el-radio-group v-model="form.front_end_show">
                  <el-radio label="0">否</el-radio>
                  <el-radio label="1">是</el-radio>
                </el-radio-group>
              </el-form-item>
              <el-form-item label="可发放数量：" prop="num">
                <el-input
                  class="wid240"
                  v-model="form.num"
                  placeholder="可发放数量"
                ></el-input>
              </el-form-item>
              <div class="el-form-item el-form-item--small">
                <label for="" class="el-form-item__label" style="width: 110px"
                  ><div>有效期：</div></label
                >
                <div class="el-form-item__content" style="margin-left: 110px">
                  <div class="validity">
                    <el-radio v-model="form.expire_type" label="1">{{
                      ""
                    }}</el-radio>
                    <el-form-item
                      label="固定日期内："
                      prop="time"
                      :rules="{
                        required: form.expire_type == 1 ? true : false,
                        message: '有效日期不能为空',
                        trigger: 'blur',
                      }"
                      label-width="110px"
                    >
                      <el-date-picker
                        v-model="form.time"
                        type="daterange"
                        range-separator="至"
                        start-placeholder="开始日期"
                        end-placeholder="结束日期"
                        value-format="yyyy-MM-dd"
                        format="yyyy-MM-dd"
                        :disabled="form.expire_type != 1 ? true : false"
                        :picker-options="pickerOptions"
                      >
                      </el-date-picker>
                    </el-form-item>
                  </div>
                  <div class="validity">
                    <el-radio v-model="form.expire_type" label="2">{{
                      ""
                    }}</el-radio>
                    <span class="span1">发放后</span>
                    <el-form-item prop="expire_days" label-width="0">
                      <!-- <el-input v-model="form.expire_days"></el-input> -->
                      <el-input-number
                        v-model="form.expire_days"
                        :controls="false"
                        :disabled="form.expire_type != 2 ? true : false"
                      ></el-input-number>
                    </el-form-item>
                    <span class="span2">天内有效</span>
                  </div>
                </div>
              </div>
              <el-form-item prop="name">
                <div slot="label">
                  领取数量限制<el-tooltip
                    class="item marginRight5 mainor_tei"
                    effect="dark"
                    placement="top"
                  >
                    <div slot="content">
                      每个用户能重复领取（含后台发放）的最大数量
                    </div>
                    <i class="el-icon-question"></i></el-tooltip
                  >：
                </div>

                <el-radio v-model="form.get_limit" label="0">不限制</el-radio>
                <el-radio v-model="form.get_limit" label="1">
                  最多可领取
                  <el-input-number
                    class="limit_number"
                    v-model="form.get_num"
                    :min="Number(0)"
                    :controls="false"
                    :disabled="form.get_limit != 1"
                  ></el-input-number
                  >张
                </el-radio>
              </el-form-item>
              <el-form-item label="订单金额限制：" prop="order_money_limit">
                <p v-show="form.type == 1" style="color: #606266">
                  订单金额满
                  <el-input-number
                    class="limit_number"
                    v-model="form.order_money_limit"
                    :min="Number(parseFloat(form.money) + 0.01)"
                    :controls="false"
                  ></el-input-number
                  >元使用
                </p>
                <p v-show="form.type == 2" style="color: #606266">不限制</p>
              </el-form-item>
              <el-form-item prop="activity_add">
                <div slot="label">
                  活动叠加<el-tooltip
                    class="item marginRight5 mainor_tei"
                    effect="dark"
                    placement="top"
                  >
                    <div slot="content">
                      是否允许参与了满减满赠，限时特卖活动的订单使用
                    </div>
                    <i class="el-icon-question"></i></el-tooltip
                  >：
                </div>
                <el-radio-group v-model="form.activity_add">
                  <el-radio label="0">可叠加</el-radio>
                  <el-radio label="1">不可叠加</el-radio>
                </el-radio-group>
              </el-form-item>
              <el-form-item label="商品限制：" prop="goods_limit">
                <el-radio-group v-model="form.goods_limit">
                  <el-radio :label="0">不限制</el-radio>
                  <el-radio :label="1">指定商品</el-radio>
                  <el-radio :label="2">排除商品</el-radio>
                </el-radio-group>
              </el-form-item>
            </div>
            <div
              class="goods_container marginLeft20 marginRight20"
              v-if="form.goods_limit == 1 || form.goods_limit == 2"
            >
              <div class="goods_container_header">
                <el-form-item label="商品名称：">
                  <el-autocomplete
                    v-model="goods_name"
                    ref="searchSelect"
                    class="wid240 main_comm"
                    :trigger-on-focus="false"
                    @clear="$refs.searchSelect.$children[0].blur()"
                    :fetch-suggestions="
                      (queryString, cb) => {
                        querySearchAsync(queryString, cb);
                      }
                    "
                    placeholder="商品/助记码/编码"
                    clearable
                    :highlight-first-item="true"
                    value-key="name"
                    @select="
                      (item) => {
                        handleSelect(item);
                      }
                    "
                  >
                    <template slot-scope="{ item }">
                      <div class="main_name">
                        <span
                          >{{ item.goods.name }}【{{
                            item.spu_name ? item.spu_name.title : ""
                          }}】</span
                        >
                        <span class="main_addr">{{ item.goods_spu_code }}</span>
                      </div>
                    </template>
                  </el-autocomplete>
                </el-form-item>
              </div>
              <div class="goods_container_body main_table">
                <el-table
                  ref="multipleTable"
                  :data="list"
                  element-loading-text="加载中"
                  fit
                  border
                  highlight-current-row
                >
                  <el-table-column label="序号">
                    <template slot-scope="scope">{{
                      scope.$index + 1
                    }}</template>
                  </el-table-column>
                  <el-table-column
                    label="商品名称"
                    prop="goods_name"
                    :show-overflow-tooltip="true"
                  >
                    <template slot-scope="scope">
                      <div>
                        {{ scope.row.goods_name }}【{{ scope.row.spu_name }}】
                      </div>
                    </template>
                  </el-table-column>
                  <el-table-column
                    label="单位"
                    prop="unit"
                    :show-overflow-tooltip="true"
                  />
                  <el-table-column
                    label="市场价"
                    prop="price"
                    :show-overflow-tooltip="true"
                  />
                  <el-table-column
                    label="管理操作"
                    prop="name"
                    width="220"
                    align="center"
                    fixed="right"
                    :show-overflow-tooltip="true"
                  >
                    <template slot-scope="scope">
                      <el-link @click="handeleDel(scope.$index)">删除</el-link>
                    </template>
                  </el-table-column>
                </el-table>
              </div>
            </div>
            <div class="clearfix"></div>
            <div class="newConBox_p200 paddingBottom10" id="newConBox">
              <div class="newConBox_h32">
                <div :class="['boxdq newConBox ', { on: searchBarFixed }]">
                  <div class="mainor_prl">
                    <el-button
                      type="primary"
                      @click="preservation"
                      v-repeatClick
                      >保存</el-button
                    >
                    <el-button
                      class="reset marginLeft10"
                      type="info"
                      v-repeatClick
                      @click="$router.back(-1)"
                      >取消</el-button
                    >
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </el-form>
  </div>
</template>
<script>
import rules from "@/rules/marketing/marketing_coupons.js";
import { apiUrl, objKeySort, Md5 } from "@/utils/public";
import { get_full_getGoodsSpu } from "@/api/marketing/marketing.js";
import { parseTime } from "@/utils/index";
import {
  get_coupons_edit,
  get_coupons_info,
} from "@/api/marketing/marketing_coupon.js";
export default {
  name: "",
  data() {
    return {
      rules,
      parseTime,
      id: "",
      form: {
        title: "",
        type: "1", //1  普通券  2  现金券
        describe: "",
        money: "", //金额
        num: "", //数量
        grant_type: "1", //1  后台  2用户领取  3新用户
        expire_type: "1", //1 固定日期  2 固定天数
        time: [],
        start_time: "",
        end_time: "",
        expire_days: "", //固定天数
        get_limit: "0", //领取限制 0 不限制 1限制
        get_num: "", //限制数量
        order_money_limit_radio: "",
        order_money_limit: "", //使用金额限制
        activity_add: "0", //活动叠加 0 可叠加 1不可叠加
        goods_limit: "", //0 不限制 1 部分使用 2 排除商品
        goods_data: "", //商品数据
        front_end_show: "0",
      },
      goods_name: "",
      pickerOptions: {
        disabledDate(time) {
          return time.getTime() < Date.now();
        },
      },
      number: "",
      list: [],
      // 监听滚动
      searchBarFixed: false,
      listLoading: false,
      isEdit: false,
    };
  },
  watch: {
    form: {
      handler(val) {
        if (val.type == 1 && !val.order_money_limit) {
          val.order_money_limit = this.$toFixed(parseFloat(val.money) + 0.01);
        }
      },
      deep: true,
    },
  },
  methods: {
    // 监听滚动
    handleScroll() {
      let scrollTop =
        window.pageYOffset ||
        document.documentElement.scrollTop ||
        document.body.scrollTop;
      scrollTop + document.documentElement.clientHeight >
      document.getElementById("newConBox").offsetTop + 200
        ? (this.searchBarFixed = false)
        : (this.searchBarFixed = true);
    },
    // 获取商品
    querySearchAsync(queryString, cb) {
      let name = queryString || "";
      let data = Object.assign(
        {
          sign: Md5(
            objKeySort(Object.assign(apiUrl().name)) + apiUrl().appsecret
          ),
        },
        apiUrl().name,
        {
          name: name,
          status: 1,
        }
      );
      get_full_getGoodsSpu(data).then((res) => {
        if (res.errcode == 0) {
          if (this.$refs.searchSelect) {
            this.$refs.searchSelect.activated = true;
          }
          var results = res.data.list;
          cb(results);
        } else {
          this.$message.error(res.errmsg);
          cb([]);
        }
      });
    },
    // 商品选择
    handleSelect(item) {
      let obj = {
        goods_id: item.goods_id,
        goods_spu_id: item.id,
        goods_name: item.goods.name,
        spu_name: item.spu_name.title,
        unit: item.spu_unit.title,
        price: item.market_price,
      };
      let flag = false;
      this.list.map((e) => {
        if (e.goods_spu_id == item.id) {
          flag = true;
        }
      });
      flag ? "" : this.list.push(obj);
      this.isEdit = true;
    },
    handeleDel(index) {
      this.list.splice(index, 1);
      this.isEdit = true;
    },
    // 保存
    preservation() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          let money_diff = this.$toFixed(
            parseFloat(this.form.order_money_limit) -
              parseFloat(this.form.money)
          );
          if (this.form.type == 1 && money_diff <= 0) {
            this.$message.warning("订单金额需要大于优惠券面值");
            return;
          }
          if (
            this.form.expire_type == 2 &&
            Number(this.form.expire_days) <= 0
          ) {
            this.$message.warning("优惠券有效期天数需大于0");
            return;
          }
          if (this.form.get_limit == 1 && Number(this.form.get_num) <= 0) {
            this.$message.warning("优惠券领取数量需要大于0");
            return;
          }
          if (this.form.goods_limit != 0 && this.list.length == 0) {
            let message = "";
            message =
              this.form.goods_limit == 1
                ? "请选择需要指定的商品"
                : "请选择需要除的商品";
            this.$message.warning(message);
            return;
          }
          let form = this.handeleData();
          let data = Object.assign(
            {
              sign: Md5(
                objKeySort(Object.assign(apiUrl().name)) + apiUrl().appsecret
              ),
            },
            apiUrl().name,
            form,
            { id: this.id }
          );
          get_coupons_edit(data).then((res) => {
            if (res.errcode == 0) {
              this.$message.success("添加成功");
              this.isEdit = false;
              this.$router.back(-1);
            } else {
              this.$message.error(res.errmsg);
            }
          });
        } else {
        }
      });
    },
    // 处理数据保存到数据库
    handeleData() {
      let form = JSON.parse(JSON.stringify(this.form));
      form.goods_data = JSON.stringify(this.list);
      form.start_time = form.time ? form.time[0] : "";
      form.end_time = form.time ? form.time[1] : "";
      delete form.time;
      return form;
    },
    // 获取信息
    get_coupons_info() {
      this.listLoading = true;
      let data = Object.assign(
        {
          sign: Md5(
            objKeySort(Object.assign(apiUrl().name)) + apiUrl().appsecret
          ),
        },
        apiUrl().name,
        { id: this.id }
      );
      get_coupons_info(data).then((res) => {
        if (res.errcode == 0) {
          let info = res.data.info;
          this.form.type = String(info.type);
          this.form.title = info.title;
          this.form.describe = info.describe;
          this.form.money = info.money;
          this.form.num = info.num;
          this.form.grant_type = String(info.grant_type);
          this.form.expire_type = String(info.expire_type);
          if (this.form.expire_type == 1) {
            let time1 = this.parseTime(info.start_time, "{y}-{m}-{d}");
            let time2 = this.parseTime(info.end_time, "{y}-{m}-{d}");
            this.form.time = [time1, time2];
          }
          this.form.expire_days = info.expire_days;
          this.form.get_limit = String(info.get_limit);
          this.form.get_num = info.get_num;
          this.form.order_money_limit = info.order_money_limit;
          this.form.activity_add = String(info.activity_add);
          this.form.front_end_show = String(info.front_end_show);
          this.form.goods_limit = info.goods_limit;
          this.list = JSON.parse(info.goods_data);
        } else {
          this.$message.error(res.errmsg);
        }
        this.listLoading = false;
      });
    },
  },
  created() {
    if (this.$route.params.id) {
      this.id = this.$route.params.id;
    }
    this.get_coupons_info();
  },
  beforeRouteLeave(to, from, next) {
    if (this.isEdit) {
      setTimeout(() => {
        this.$confirm(
          "您已经有数据操作，离开页面系统不会保存您的操作，确定离开吗？",
          "提示",
          {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning",
          }
        )
          .then(() => {
            next();
          })
          .catch(() => {
            next(false);
          });
      }, 200);
    } else {
      next();
    }
  },
  mounted() {
    let scrollTop =
      window.pageYOffset ||
      document.documentElement.scrollTop ||
      document.body.scrollTop;
    scrollTop + document.documentElement.clientHeight >
    document.getElementById("newConBox").offsetTop + 200
      ? (this.searchBarFixed = false)
      : (this.searchBarFixed = true);
    window.addEventListener("scroll", this.handleScroll);
  },
  destroyed() {
    window.removeEventListener("scroll", this.handleScroll);
  },
};
</script>
<style lang='scss' scoped>
.validity {
  display: flex;
  align-items: center;
  flex-direction: row;
  &:first-child {
    margin-bottom: 18px;
  }
  /deep/ .el-form-item--mini.el-form-item,
  .el-form-item--small.el-form-item {
    margin-bottom: 0;
  }
  /deep/ .el-radio {
    margin-right: 10px;
    transform: translateY(1px);
  }
  span {
    font-size: 14px;
    color: #606266;
    display: inline-block;
    // padding-left: 15px;
    &.span1 {
      padding-left: 15px;
      padding-right: 10px;
    }
    &.span2 {
      padding-left: 10px;
    }
  }
}
.limit_number {
  margin: 0 10px;
}
.save_container {
  padding: 0 20px;
  margin-top: 15px;
  &.positive {
    position: fixed;
    bottom: 50px;
    left: 0;
    z-index: 9999;
  }
}
.newConBox.on {
  margin-left: -10px;
  padding-left: 10px;
}
.main_name {
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  padding: 5px 0;
  height: 50px;

  .main_addr {
    color: #999;
  }

  span {
    line-height: 20px;
    display: inline;
    height: 20px;
  }
}
</style>
